<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="formData" v-loading="isLoading">
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-input v-model="formData.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色编码" :label-width="formLabelWidth">
        <el-input v-model="formData.code" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input
          v-model="formData.description"
          autocomplete="off"
          type="textarea"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getRole, saveOrUpdate } from '@/api/role'

export default {
  name: 'RoleCreateOrEdit',
  data () {
    return {
      isLoading: false,
      isCreate: true,
      dialogFormVisible: false,
      formData: {
        id: undefined,
        name: '',
        code: '',
        description: ''
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    title () {
      return this.isCreate ? '添加角色' : '编辑角色'
    }
  },
  methods: {
    onSubmit () {
      saveOrUpdate(this.formData)
        .then((res) => {
          if (res.data.code === '000000') {
            this.$message.success(`${this.title}成功！`)
            this.$emit('role-change')
          } else {
            this.$message.error(`${this.title}失败`)
          }
        })
        .finally(() => {
          this.dialogFormVisible = false
        })
    },
    showAndInit (roleId) {
      this.formData.id = roleId
      this.isCreate = !roleId
      this.dialogFormVisible = true
      if (this.isCreate) {
        this.formData = {}
      } else {
        this.isLoading = true
        getRole(roleId)
          .then((res) => {
            if (res.data.code === '000000') {
              Object.assign(this.formData, res.data.data)
            }
          })
          .finally(() => {
            this.isLoading = false
          })
      }
    }
  }
}
</script>
<style scoped lang="scss">
</style>
